package com.mc.book.controller;

import com.mc.book.enums.ResponseEnum;
import com.mc.book.pojo.Result;
import com.mc.book.redis.RedisService;
import com.mc.book.service.UserService;
import com.mc.book.utils.wxgzh.WxGzhProperties;
import com.mc.book.utils.wxgzh.WxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/weixin")
public class WxInitController extends BaseApi{
    private static final Logger log = LoggerFactory.getLogger(WxInitController.class);
    @Autowired
    RedisService redis;

    @Autowired
    UserService userService;

    /**
     *@Author: hdx
     *@CreateTime: 20:39 2020/2/14
     *@param:  shareUrl 分享url地址
     *@Description: 初始化微信JSSDK Config信息
    1.先通过appId和appSecret参数请求指定微信地址 获取AccessToken
    2.在通过第一步中的AccessToken作为参数请求微信地址 获取jsapi_ticket临时票据(此处不考虑调用频率，使用者根据情况放入缓存或定时任务)
    3.通过第二步的JssdkGetticket和timestamp,nonceStr,url作为参数请求微信地址，获取签名signature
    4.将第三步获得的signature和jsapi_ticket,nonceStr,timestamp,url返回给前端，作为Config初始化验证的信息
     */
    @RequestMapping("/initWXJSSDKConfigInfo")
    public Result initWXJSConfig (@RequestParam(required = false) String url){
        try {
            log.info("url=" + url);
            String json = "";
            String wxAccessToken = redis.getObject("wxAccessToken", String.class);
            if(null == wxAccessToken){
                wxAccessToken = WxUtil.getJSSDKAccessToken();
                redis.add("wxAccessToken",wxAccessToken,7100,TimeUnit.SECONDS);
            }
            //获取JssdkGetticket
            String jsapiTicket = redis.getObject("jsapiTicket", String.class);
            if(null == jsapiTicket){
                jsapiTicket = WxUtil.getJssdkGetticket(wxAccessToken);
                redis.add("jsapiTicket",jsapiTicket,7100,TimeUnit.SECONDS);
            }

            String timestamp = Long.toString(System.currentTimeMillis() / 1000);
            String nonceStr = UUID.randomUUID().toString();
            String signature = WxUtil.buildJSSDKSignature(jsapiTicket,timestamp,nonceStr,url);
            Map<String,String> map = new HashMap<String,String>();
            map.put("url", url);
            map.put("jsapi_ticket", jsapiTicket);
            map.put("nonceStr", nonceStr);
            map.put("timestamp", timestamp);
            map.put("signature", signature);
            map.put("appid", WxUtil.getAppId());

//            json = WxUtil.mapToJson(map);
            return Result.success(map);
        }catch (Exception e){
            log.error("系统异常：", e);
            return Result.fail(ResponseEnum.UP_SYSTEM_FAILURE.getCode(),ResponseEnum.UP_SYSTEM_FAILURE.getMessage());
        }
    }

    @RequestMapping("/gzhOpenid")
    public Result gzhOpenid (@RequestParam("code") String code,@RequestParam("user_phone") String user_phone){
        try {
            log.info("code=" + code);
            log.info("user_phone=" + user_phone);
            String openid = WxUtil.getOpenid(code);
            if(null != openid){
                userService.openidUpDate(user_phone,openid);
            }
            Map<String,String> map = new HashMap<String,String>();
            map.put("openid", openid);

            return Result.success(map);
        }catch (Exception e){
            log.error("系统异常：", e);
            return Result.fail(ResponseEnum.UP_SYSTEM_FAILURE.getCode(),ResponseEnum.UP_SYSTEM_FAILURE.getMessage());
        }
    }

}
